package com.example.preventlosing;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class TCPClient extends Thread {
	
	private SearchActivity sa;
	private InputStream is;
	private OutputStream os;
	private ObjectInputStream ois;
	ObjectOutputStream oos;
	String serverAddress;
	String stringMsg;
	
	Socket socket = null;
	String rMsg = "";
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			super.handleMessage(msg);

			
		}
	};
	
	public TCPClient(SearchActivity sa,String ip, String what) {
		this.sa =sa;
		serverAddress = ip;
		stringMsg =what;
	}
	

	public void run() {
		
		String re = "";
		
		try {
			Log.e("add",serverAddress);
			socket = new Socket(serverAddress,3007);
			sendMessage(socket,stringMsg);
			if(stringMsg.equals("gps")){
				re = receiveMessage(socket);
				Log.e("re",re);
				sa.startIntent(re);
			}
			else if(stringMsg.equals("sound")){
				
			}
			else if(stringMsg.equals("camera")){
				byte[] imageData = receiveImage(socket);
				sa.startImageIntent(imageData);
			}
			socket.close();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
//		finally {
//			try {
//				socket.close();
//			}
//			catch(Exception e) {
//				e.printStackTrace();
//			}
//		}
		
	}
	
	public String receiveMessage(Socket socket) {
		try {
			is = socket.getInputStream();
			ois = new ObjectInputStream(is);
			if(stringMsg.equals("gps")){
				rMsg = (String)ois.readObject();
				Log.e("receivedMessage",rMsg);
			}
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		return rMsg;
	}
	
	public byte[] receiveImage(Socket socket) {
		byte[] image = null;
		try {
			is = socket.getInputStream();
			ois = new ObjectInputStream(is);
			if(stringMsg.equals("camera")){
				image = (byte[])ois.readObject();
			}
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		return image;
	}
	
	private void sendMessage(Socket socket,String what) {
		try {
			os = socket.getOutputStream();
			oos = new ObjectOutputStream(os);
			String sMsg = what;
			oos.writeObject(sMsg);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
	

}
